import browser from "webextension-polyfill";

import type { Tabs } from "webextension-polyfill";

import { setSpotMarketSystemRequest } from "./request";
import { closeOtherTabs, getTabMark, saveMainSystemHeaders, saveSportMarketHeaders, saveSportMarketZcqHeaders, saveStorageUserinfo } from "./utils/common";
import { SD_SYSTEM } from "@src/globalData/enum";
import { userUnitid } from "@src/config/accountInfo";

const promiseTimeout = (timeOut:number = 1000) => {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, timeOut)
  })
}

/** 去子系统种的 请求数据需要的headers */
export async function sendMessageGetHeadersToTab(tab: Tabs.Tab, mark:string) {
    if(!tab.id) return Promise.reject(new Error('Tab doesn"t have id'))

    try {
      const headers:HeadersInit = await browser.tabs.sendMessage(tab.id, { type: 'GetHeaders', mark })

      if(mark === SD_SYSTEM.SPOT_MARKET) saveSportMarketHeaders(headers)
      if(mark === SD_SYSTEM.MAIN) saveMainSystemHeaders(headers)
      return Promise.resolve(headers)
    }catch(e) {
      console.error(e)
      return Promise.reject(e)
    }
}

/** 去子系统 中长期 的 请求数据需要的headers */
export async function sendMessageGetZcqHeadersToTab(tab: Tabs.Tab, mark:string) {
    if(!tab.id) return Promise.reject(new Error('Tab doesn"t have id'))

    try {
      const headers:HeadersInit = await browser.tabs.sendMessage(tab.id, { type: 'GetZcqInfo', mark })

      if(mark === SD_SYSTEM.SPOT_MARKET_ZCQ) saveSportMarketZcqHeaders(headers)
      return Promise.resolve(headers)
    }catch(e) {
      console.error(e)
      return Promise.reject(e)
    }
}

/** 去主系统获取用户信息 */
export async function sendMessageGetUserInfo(mark:string) {
    try {
      const tabs = await browser.tabs.query({})
      const tab = tabs.find(val => getTabMark(new URL(val?.url || '')) === mark)
      if(!tab?.id) {
        console.error('获取主系统 tab 失败， 请打开主系统')
        return Promise.resolve(false)
      }

      const userInfo = await browser.tabs.sendMessage(tab.id, { type: 'GetUserInfo', mark})
      if(userInfo?.userName !== import.meta.env.VITE_APP_ACCOUNT) {
        saveStorageUserinfo('')
        const errTip = '实际账号与打包配置账号不一致'
        console.error(errTip)
        return Promise.reject(new Error(errTip))
      }
      saveStorageUserinfo(userInfo)
      return Promise.resolve(userInfo)
    }catch(e) {
      console.error(e)
      return Promise.reject(e)
    }
}

/** tab 更新时触发执行的方法 */
async function tabUpdate(tabId: number, changeInfo:Tabs.OnUpdatedChangeInfoType, tab: Tabs.Tab) {
  if(changeInfo.status === "loading") return
  const url = new URL(tab?.url || '')
  await promiseTimeout(5000)

  const mark = getTabMark(url)
  
  console.log('tabUpdate', mark)

  const CHILD_SYSTEM = import.meta.env.VITE_APP_CHILD_SYSTEM
  
  switch(mark){
    case SD_SYSTEM.SPOT_MARKET: {
        if(SD_SYSTEM.SPOT_MARKET !== CHILD_SYSTEM) {
          console.error(`此打包只为子系统：现货市场 ${CHILD_SYSTEM}`)
          return Promise.resolve()
        }
        const headers = await sendMessageGetHeadersToTab(tab, mark)

        const userInfo = await sendMessageGetUserInfo(SD_SYSTEM.MAIN)
        let unitid = userUnitid?.[userInfo?.userName] || ''

        if(!unitid) {
          console.error('此账号未配置 unitid, 请打开 【现货市场】-【现货交易】-【日前交易结果】-【一次日前交易结果查询】')
          unitid = await sendMessageGetUserInfo(SD_SYSTEM.SPOT_MARKET)
        }

        if(import.meta.env.VITE_APP_GETDATA_WAY !== 'auto') {
          console.error(`${import.meta.env.VITE_APP_GETDATA_WAY} 打包环境不能自动启动 自动获取现货市场系统的数据`)
          return
        }
        setSpotMarketSystemRequest(headers, mark, unitid)
        break;
      }
    case SD_SYSTEM.LOGIN_MAIN:
    case SD_SYSTEM.MAIN:{
      tab?.id && closeOtherTabs(tab.id)

      // const headers = await sendMessageGetHeadersToTab(tab, mark)
      // const userInfo = await sendMessageGetUserInfo(mark)
      // // let unitid = userUnitid?.[userInfo?.userName] || ''

      // getMainSystemPrivateDataThrottle({headers, userInfo})
      break;
    }
    case SD_SYSTEM.SPOT_MARKET_ZCQ: {
      if(SD_SYSTEM.SPOT_MARKET_ZCQ !== CHILD_SYSTEM) {
        console.error(`此打包只为子系统：现货市场中长期 ${CHILD_SYSTEM}`)
        return Promise.resolve()
      }

      const headers = await sendMessageGetZcqHeadersToTab(tab, mark)
      const userInfo = await sendMessageGetUserInfo(SD_SYSTEM.MAIN)

      const unitid = userInfo?.memberId

      setSpotMarketSystemRequest(headers, mark, unitid)
      break;
    }
    default:
      break;
  }
}

/** 在 background 监听 tab */
export function bindTabUpdatedEvent() {
  /**Chrome 插件开发中用于监听标签页更新事件的方法 */
  browser.tabs.onUpdated.addListener(tabUpdate)
}

